package xyz.ibenben.zhongdian.system.controller;

import org.springframework.beans.propertyeditors.CustomBooleanEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import xyz.ibenben.zhongdian.system.entity.HouseStatus;
import xyz.ibenben.zhongdian.system.entity.OtherRightDigest;
import xyz.ibenben.zhongdian.system.entity.PropertyOwnershipCertificate;
import xyz.ibenben.zhongdian.system.service.PropertyOwnershipCertificateService;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 总控制类
 * 提供了一些基本的服务，如数据转换、公共方法等方法。
 * spring mvc思想 通过controller来调用service里的方法，
 * service里的方法再通过调用Dao来实现对数据的操作
 * 返回值统统是String类型的返回页面有统一的安排方便代码提取
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
public class BaseController {
	/**
	 * 数据转换
	 * @param binder 转换器
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		//转换日期
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// CustomDateEditor为自定义日期编辑器
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
		binder.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, true));
		binder.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class, true));
		binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, true));
		binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
		binder.registerCustomEditor(Boolean.class, new CustomBooleanEditor(true));
	}

	/**
	 * 公共方法
	 * @param map 参数
	 * @param ownerId 所有者主键
	 * @param obj 实体类
	 * @param propertyOwnershipCertificateService 产权服务
	 */
	public void setPropertyOwnershipCertificate(Model map, Long ownerId, Object obj,
			PropertyOwnershipCertificateService propertyOwnershipCertificateService){
		if(ownerId != null){
			//查看传过来的类属于哪个实体
			if(obj instanceof HouseStatus){
				HouseStatus houseStatus = (HouseStatus)obj;
				houseStatus.setOwnerId(ownerId);
				houseStatus.setFromOwnerId(true);
			}else{
				OtherRightDigest otherRightDigest = (OtherRightDigest)obj;
				otherRightDigest.setOwnerId(ownerId);
				otherRightDigest.setFromOwnerId(true);
			}
		}else{
			//获取所有的产权信息，放到页面上
			List<PropertyOwnershipCertificate> list = propertyOwnershipCertificateService.selectAll();
			map.addAttribute("propertyOwnershipCertificateList", list);
		}
	}

}
